package com.xydtech.ecard.ecard.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xydtech.common.annotation.PassToken;
import com.xydtech.common.annotation.RsaRequest;
import com.xydtech.common.constant.UserConstants;
import com.xydtech.common.core.domain.entity.SysUser;
import com.xydtech.common.enums.ApiContant;
import com.xydtech.common.enums.ResultStatus;
import com.xydtech.common.model.ResponseModel;
import com.xydtech.common.utils.DateUtils;
import com.xydtech.common.utils.ShiroUtils;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.ecard.ecard.domain.EcardApiExperienceApprove;
import com.xydtech.ecard.ecard.domain.EcardApiExperienceUser;
import com.xydtech.ecard.ecard.service.IEcardApiExperienceApproveService;
import com.xydtech.ecard.ecard.service.IEcardApiExperienceUserService;
import com.xydtech.ecard.user.domain.EcardApiEcardRegistInfo;
import com.xydtech.ecard.user.domain.EcardApiUserInfo;
import com.xydtech.ecard.user.service.IEcardApiEcardRegistInfoService;
import com.xydtech.ecard.user.service.IEcardApiUserService;
import com.xydtech.system.domain.SysWechatApplet;
import com.xydtech.system.service.ISysUserService;
import com.xydtech.system.service.ISysWechatAppletService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * 电子名片用户申请体验Controller
 *
 * @author yuzhiguo
 * @date 2024-10-23 上午8:51
 */
@Controller
@Slf4j
@Api(tags = "电子名片-用户申请体验接口")
@RequestMapping("/ecardSaasApi/experienceUser")
public class EcardApiExperienceUserController extends EcardApiBaseController {

    //4:客户经理
    private static String roles = "4";
    //客户经理岗位，后台没维护，这里用不到
    private static String cm = "cm";
    //网格管理员岗位
    private static String wg = "wg";

    @Autowired
    private IEcardApiExperienceUserService ecardExperienceUserService;
    @Autowired
    private IEcardApiExperienceApproveService ecardExperienceApproveService;
    @Autowired
    private IEcardApiUserService ecardApiUserService;
    @Autowired
    private IEcardApiEcardRegistInfoService ecardRegistInfoService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysWechatAppletService sysWeChatAppletService;

    /**
     * 电子名片-保存用户申请体验数据接口
     *
     * @author yuzhiguo
     * @date 2024/10/23 上午9:16
     */
    @PassToken
    @PostMapping(value = "/addExperienceUserInfo")
    @ApiOperation(value = "电子名片-保存用户申请体验数据接口", notes = "电子名片-保存用户申请体验数据接口")
    @ResponseBody
    @RsaRequest(result = false)
    public ResponseModel addExperienceUserInfo(@RequestBody EcardApiExperienceUser ecardExperienceUser) {
        log.info("接口请求时间-------" + DateUtils.getTime());
        try {
            String salt = getSalt();//盐值
            String openId = getOpenIdByCode(ecardExperienceUser.getAppId(), ecardExperienceUser.getCode());
            //根据openid查询体验表中状态不为3（拒件）的数据，有的话不能重复提交
            List<EcardApiExperienceUser> experienceUserList = ecardExperienceUserService.verifyExperienceUser(openId, "", salt);
            EcardApiEcardRegistInfo ecardRegistInfo = ecardRegistInfoService.selectEcardApiEcardRegistInfoByOpenId(openId, salt);
            //根据openid校验体验表和注册表中是否有数据
            if (experienceUserList.size() > 0 || ecardRegistInfo != null){
                return ResponseModel.error("不能重复提交申请！");
            }
            //根据手机号查询体验表中状态不为3（拒件）的数据，有的话不能重复提交
            List<EcardApiExperienceUser> experienceList = ecardExperienceUserService.verifyExperienceUser("", ecardExperienceUser.getExpPhone(), salt);
            //根据手机号校验体验表是否有数据
            if (experienceList.size() > 0){
                return ResponseModel.error("不能重复提交申请！");
            }
            //用户表中已有数据的不允许申请
            SysUser sysUser = userService.selectUserByPhoneNumber(ecardExperienceUser.getExpPhone(), salt);
            if (sysUser != null){
                return ResponseModel.error("已存在该用户信息！");
            }
            //保存用户申请体验数据，默认状态为待审批
            ecardExperienceUser.setOpenId(openId);
            int id = ecardExperienceUserService.addExperienceUserInfo(ecardExperienceUser, salt);
            log.info("接口返回时间-------" + DateUtils.getTime());
            return id > 0 ? ResponseModel.ok() : ResponseModel.error("添加失败！");
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-条件查询查询待审批状态下的用户申请体验数据列表
     *
     * @author yuzhiguo
     * @date 2024/10/23 上午9:54
     */
    @PostMapping(value = "/getExperienceUserList")
    @ApiOperation(value = "电子名片-条件查询查询待审批状态下的用户申请体验数据列表", notes = "电子名片-条件查询查询待审批状态下的用户申请体验数据列表")
    @ResponseBody
    @RsaRequest
    public ResponseModel getExperienceUserList(@RequestBody String json) {
        log.info("接口请求时间-------" + DateUtils.getTime());
        try {
            String salt = getSalt();//盐值
            JSONObject jsonObject = JSONObject.parseObject(json);
            String expName = jsonObject.getString("expName");
            String expPhone = jsonObject.getString("expPhone");
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");

            EcardApiExperienceUser experienceUser = new EcardApiExperienceUser();
            experienceUser.setExpName(expName);
            experienceUser.setExpPhone(expPhone);
            experienceUser.setState("1");//体验申请状态，1：待审批，2：审批成功，3：拒件
            PageHelper.startPage(pageNum, pageSize);
            List<EcardApiExperienceUser> experienceUserList = ecardExperienceUserService.getExperienceUserList(experienceUser, salt);
            PageInfo pageInfo = new PageInfo(experienceUserList);
            log.info("接口返回时间-------" + DateUtils.getTime());
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), experienceUserList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-查询用户申请体验数据详情
     *
     * @author yuzhiguo
     * @date 2024/10/23 上午10:03
     */
    @PostMapping("/getExperienceUserInfo")
    @ApiOperation(value = "电子名片-查询用户申请体验数据详情", notes = "电子名片-查询用户申请体验数据详情")
    @ResponseBody
    @RsaRequest
    public ResponseModel getExperienceUserInfo(@RequestBody String json) {
        log.info("接口请求时间-------" + DateUtils.getTime());
        try {
            String salt = getSalt();//盐值
            //根据id查询申请体验数据，用于审批
            JSONObject jsonObject = JSONObject.parseObject(json);
            Long id = jsonObject.getLong("id");
            if (StringUtils.objIsNullOrEmpty(id)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            EcardApiExperienceUser experienceUser = ecardExperienceUserService.getExperienceUserInfo(id, salt);
            log.info("接口返回时间-------" + DateUtils.getTime());
            return ResponseModel.okToJSON(experienceUser);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-审批用户申请体验数据接口
     *
     * @author yuzhiguo
     * @date 2024/10/23 上午10:09
     */
    @PostMapping(value = "/approveExperienceUser")
    @ApiOperation(value = "电子名片-审批用户申请体验数据接口", notes = "电子名片-审批用户申请体验数据接口")
    @ResponseBody
    @RsaRequest(result = false)
    public ResponseModel approveExperienceUser(@RequestBody EcardApiExperienceUser ecardExperienceUser) {
        log.info("接口请求时间-------" + DateUtils.getTime());
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            String expPhone = ecardExperienceUser.getExpPhone();
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
            //审批保存更新申请体验数据状态
            int id = ecardExperienceUserService.updateEcardExperienceUser(ecardExperienceUser, salt);

            //审批结果为2-审批成功时，往用户表里插入一条用户信息用户名称，手机号，员工号，机构，主岗位为2客户经理，是否为体验人员字段为是
            if ("2".equals(ecardExperienceUser.getState())){
                log.info("==================新增用户前expPhone：" + expPhone);
                SysUser user = new SysUser();
                user.setUserName(ecardExperienceUser.getExpName());//用户名称
                user.setDeptId(140L);//归属机构，默认为测试机构
                user.setPhonenumber(expPhone);//手机号码
                user.setLoginName(expPhone);//登录账号
                user.setSalt(ShiroUtils.randomSalt());
                user.setPassword(encryptPassword(user.getLoginName(), "123456", user.getSalt()));//登录密码，默认123456
                user.setUserCode(expPhone);//员工号
                user.setPostIds("2");//主岗位，默认客户经理
                user.setExtendPostIds("2");//拓展岗位，默认客户经理
                user.setIsExperience("T");//是否体验人员，是：T，否：F
                if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName()))) {
                    return ResponseModel.error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
                } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                        && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user, salt))) {
                    return ResponseModel.error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
                }
                log.info("==================校验后expPhone：" + expPhone);
                user.setLoginName(expPhone);//登录账号
                user.setPhonenumber(expPhone);//手机号
                user.setUserCode(expPhone);//员工号
                log.info("==================校验后user：" + user.toString());
                userService.insertUser(user, salt);

                EcardApiEcardRegistInfo registInfo = ecardRegistInfoService.selectEcardApiEcardRegistInfoByUserCode(ecardExperienceUser.getExpPhone(), salt);
                if (registInfo != null) {
                    return ResponseModel.error("该员工编号已被用户名为：" + registInfo.getWechatName() + "占用，请联系管理员进行解绑！");
                }
                //获取体验人申请时保存的微信编码
                EcardApiExperienceUser experienceUser = ecardExperienceUserService.getExperienceUserInfo(ecardExperienceUser.getId(), salt);
                EcardApiEcardRegistInfo ecardRegistInfo = new EcardApiEcardRegistInfo();
                ecardRegistInfo.setWechatId(experienceUser.getOpenId());
                ecardRegistInfo.setUserCode(expPhone);
                ecardRegistInfo.setWechatName(ecardExperienceUser.getExpName());
                ecardRegistInfo.setPhoneno(expPhone);
                //默认客户经理
                ecardRegistInfo.setRoles("4");
                log.info("==================新增注册ecardRegistInfo：" + ecardRegistInfo.toString());
                ecardRegistInfoService.insertEcardApiEcardRegistInfo(ecardRegistInfo, salt);
            }

            //往审批记录表里插入数据
            EcardApiExperienceApprove experienceApprove = new EcardApiExperienceApprove();
            experienceApprove.setExpId(ecardExperienceUser.getId());//申请信息关联id
            experienceApprove.setState(ecardExperienceUser.getState());//审批结果，1：待审批，2：审批成功，3：拒件
            experienceApprove.setCreatorId(Long.valueOf(userInfo.getRegistId()));//审批人注册id
            experienceApprove.setRemark(ecardExperienceUser.getRemark());
            ecardExperienceApproveService.insertEcardExperienceApprove(experienceApprove);

            log.info("接口返回时间-------" + DateUtils.getTime());
            return id > 0 ? ResponseModel.ok(ecardExperienceUser.getId()) : ResponseModel.error("添加失败！");
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-条件查询用户申请体验审批记录列表
     *
     * @author yuzhiguo
     * @date 2024/10/23 上午11:31
     */
    @PostMapping(value = "/getApproveExperienceList")
    @ApiOperation(value = "电子名片-条件查询用户申请体验审批记录列表", notes = "电子名片-条件查询用户申请体验审批记录列表")
    @ResponseBody
    @RsaRequest
    public ResponseModel getApproveExperienceList(@RequestBody String json) {
        log.info("接口请求时间-------" + DateUtils.getTime());
        try {
            String salt = getSalt();//盐值
            JSONObject jsonObject = JSONObject.parseObject(json);
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");

            EcardApiExperienceApprove experienceApprove = new EcardApiExperienceApprove();
            PageHelper.startPage(pageNum, pageSize);
            List<EcardApiExperienceApprove> experienceApproveList = ecardExperienceApproveService.getApproveExperienceList(experienceApprove, salt);
            PageInfo pageInfo = new PageInfo(experienceApproveList);
            log.info("接口返回时间-------" + DateUtils.getTime());
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), experienceApproveList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 登录密码加密
     * @param loginName
     * @param password
     * @param salt
     * @return
     */
    public String encryptPassword(String loginName, String password, String salt) {
        return new Md5Hash(loginName + password + salt).toHex();
    }

    /**
     * 根据code获取用户的openId
     * @Title getOpenIdByCode
     * @param code:小程序端wx.login获取到的code
     * @return java.lang.String
     * @exception
     * @author Daniel
     * @Date 2020/7/30 9:36
     **/
    private String getOpenIdByCode(String appId, String code) {

        //获取配置的小程序的appid和secret
        SysWechatApplet sysWechatApplet = sysWeChatAppletService.getWechatAppletByAppId(ApiContant.APPLETTYPE_ECARD, appId);

        String requestUrl = sysWechatApplet.getGetOpenIdUrl() + "appid=" + sysWechatApplet.getAppid() + "&secret=" + sysWechatApplet.getSecret() + "&js_code=" + code + "&grant_type=authorization_code";

        String openId = null;
        RestTemplate restTemplate = new RestTemplate();
        String loginInfoStr = restTemplate.getForObject(requestUrl, String.class);

        //获取返回内容中的openId信息
        JSONObject openIdInfoObj = JSONObject.parseObject(loginInfoStr);
        openId = openIdInfoObj.getString("openid");
        return openId;
    }
}
